#include "server.h"

int main(int argc, char const *argv[])
{
    if (2 != argc)
    {
        printf("格式错误:[%s] [port]\n",argv[0]);
        exit(1);
    }
    
    //初始化UDP
    int sock_fd = UDP_init(atoi(argv[1]));

    // 缓冲区
    char buf[1024];
    
    memset(buf, 0 , sizeof(buf));

    struct sockaddr_in client_addr;
    
    socklen_t client_len = sizeof(client_addr);

    user_data new_user;

    int name_len;

    user_list list;

    list.len = 0;

    while (1)
    {
        //清空接收缓冲区
        memset(buf, 0 ,sizeof(buf));

        //接收客户端发来的信息
        recvfrom(sock_fd,buf,sizeof(buf),0,(struct sockaddr *)&client_addr,&client_len);

        //判断是否修改名称 认定为增加用户
        if (strstr(buf , "set_name_") !=NULL)
        {
            //处理名字信息 
            strcpy(new_user.name, buf + 9);
            name_len = strlen(new_user.name);
            new_user.name[name_len - 4] = '\0';

            //写入用户信息结构体
            new_user.sock_addr = client_addr;

            //写入用户信息结构体的长度
            new_user.sock_len = sizeof(new_user.sock_addr);

            //将xx用户添加到顺序表中
            tail_insert_tail(&list, new_user);

            //群发
            memset(buf , 0 ,sizeof(buf));

            sprintf(buf, "欢迎 %s加入群聊\n",new_user.name);
            for (size_t i = 0; i < list.len; i++)
            {
                sendto(sock_fd, buf ,strlen(buf) , 0 ,(struct sockaddr *)&list.data[i].sock_addr ,new_user.sock_len);
            }
            
            continue;
        }
        
        //群发操作
    }
    

    //关闭
    UDP_close();
    return 0;
}
